<template>
	<view class="container">
		<view class="cutBox">
			<image class="avatar" :src="urls[0]" @click="chooseImage(0)"></image>
			<xy-avatar @upload="cutImage" ref="avatar"></xy-avatar>
		</view>
		<view class="action">
			<button @click="submit" type="primary">提交</button>
		</view>
	</view>
</template>

<script>
	import { mapState, mapMutations } from 'vuex';
	export default {
		computed: {
			...mapState(['app', 'user'])
		},
		data() {
			return {
				urls: [],
				avatar: ''
			}
		},
		onLoad(options){
			this.urls.push(this.user.userInfo.avatar);
		},
		methods: {
			cutImage(rsp) {
				console.log(rsp);
                this.$set(this.urls, rsp.index, rsp.path);
            },
			chooseImage(index) {
				this.$refs.avatar.fChooseImg(index,{
                    selWidth: "300upx", selHeight: "300upx",
                    expWidth: '260upx', expHeight: '260upx'
                });
			},
			async submit(){
				let fileExt = 'png';
				let res = await this.util.uploadFile({
					driver: 'upload_oss',
					filePath: this.urls[0],
					fileExt: fileExt
				});
				if (res.code == 200) {
					this.avatar = res.data.url;
					let res0 = await this.util.request({
						url: '/v1/core/user/avatar',
						data: {
							avatar: this.avatar
						},
						method: 'put',
					});
					if (res0.code == 200) {
						let userInfo = this.user.userInfo;
						userInfo.avatar = this.avatar;
						this.$store.commit('user/setUserInfo', userInfo);
						this.util.showToast({
							title: res0.msg,
							icon: 'success',
							duration: 1000
						});
						uni.navigateBack();
					} else {
						this.util.showToast({
							title: res0.msg,
							icon: 'loading',
							duration: 2000
						});
					}
				} else {
					this.util.showToast({
						title: res.msg,
						icon: 'loading',
						duration: 2000
					});
				}
			}
		}
	}
</script>

<style lang='scss'>
	page {
		background: $page-color-base;
	}
	.cutBox {
		padding-top: 60upx;
		text-align: center;
		background-color: #fff;
		border:1px solid $page-color-base;
		.avatar {
			width: 500upx;
			height: 500upx;
		}
	}
	.action {
		padding: 20px;
		button[type="primary"] {
			background-color: $uni-color-primary;
		}
	}
</style>
